package ningbo.api;

import java.util.Objects;

/**
 * @Author 宁铂
 * @Date 2021/7/17 11:06
 * @Version 1.0
 */
public class TestObject {
    /** 本类用于测试顶级父类Object */

    public static void main(String[] args) {
        Student student1 = new Student();
        Student student2 = new Student("李逵",3);
        Student student3 = new Student("李逵",3);

        System.out.println(student2);

        /** 用来区分不同的对象，不同的对象会产生不同的哈希码值
         *  查看源码：CTRL+目标位置
         * */
        System.out.println(student1.hashCode());
        System.out.println(student2.hashCode());

        System.out.println(student3.equals(student2));
    }
}


class Student{
    String name;
    int age;

    public Student() {

    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /** 原 toString 打印的是引用的地址，而我们想看到的是对象中的属性
     *  所以我们可以重写 toString 来完成我们想要的结果
     * */
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return age == student.age && Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}